import os
import shutil
from fastapi import UploadFile
from uuid import uuid4
from src.main import make_unique_output_dir
from src.parser import parse_slide
from src.gen_pptx import process_elements
from pptx import Presentation
import json

def save_upload_file(upload_file: UploadFile, destination: str):
    with open(destination, "wb") as buffer:
        shutil.copyfileobj(upload_file.file, buffer)

async def parse_pptx(file: UploadFile):
    # 保存上传的PPTX文件
    upload_dir = os.path.abspath("./uploads")
    os.makedirs(upload_dir, exist_ok=True)
    file_id = str(uuid4())
    file_path = os.path.join(upload_dir, f"{file_id}_{file.filename}")
    save_upload_file(file, file_path)

    # 解析第一页（可根据需要调整）
    prs = Presentation(file_path)
    prs.pptx_path = file_path
    slide_idx = 0
    out_dir = make_unique_output_dir("output", file_path, slide_idx+1)
    parsed = parse_slide(prs, slide_idx)
    # 保存解析结果
    layout_dir = os.path.join(out_dir, "layouts")
    os.makedirs(layout_dir, exist_ok=True)
    layout_path = os.path.join(layout_dir, f"{slide_idx+1}_布局.json")
    with open(layout_path, "w", encoding="utf-8") as f:
        json.dump(parsed, f, ensure_ascii=False, indent=2)
    return out_dir

def restore_pptx(folder_path: str):
    # 读取布局文件
    layout_dir = os.path.join(folder_path, "layouts")
    layout_files = [f for f in os.listdir(layout_dir) if f.endswith("_布局.json")]
    if not layout_files:
        raise FileNotFoundError("未找到布局文件")
    layout_path = os.path.join(layout_dir, layout_files[0])
    with open(layout_path, "r", encoding="utf-8") as f:
        layout_data = json.load(f)
    # 创建PPTX
    prs = Presentation()
    prs.slide_width = layout_data.get('slide_width', 9144000)
    prs.slide_height = layout_data.get('slide_height', 5143500)
    slide_layout = prs.slide_layouts[6]
    slide = prs.slides.add_slide(slide_layout)
    elements = layout_data['layout'] if 'layout' in layout_data else layout_data['elements']
    process_elements(slide, elements, None)
    pptx_path = os.path.join(folder_path, 'output.pptx')
    prs.save(pptx_path)
    return folder_path 